<template>
	<div class="map-container">
		<u-search height="80" placeholder="请输入搜素地址" searchIconSize="32" searchIcon="arrow-left" class="search-box" v-model="searchKey"
			:showAction="false" :animation="true" @clickIcon="back" @change="searchChange" @custom="goCustom" />
		<view class="ul">
			<view class="li" v-for="item in searchList" :key="item.id" @click="goSearch(item)">
				{{item.name}}
			</view>
		</view>
		<!-- <el-amap-search-box  :search-option="searchOption"
			:on-search-result="onSearchResult"></el-amap-search-box> -->
		<!-- 地图 -->
		<el-amap ref="map" vid="amapDemo" :amap-manager="amapManager" :center="center" :zoom="zoom" :plugin="plugin"
			:events="events" class="amap-demo">
			<!-- 标记 -->
			<el-amap-marker v-for="(marker, index) in markers" :key="'marker' + index" :position="marker.position" />
			<!-- 位置名称显示 -->
			<el-amap-text v-for="(marker, index) in markers" :key="'text' + index" :text="marker.text"
				:offset="marker.offset" :position="marker.position" />
		</el-amap>

	</div>
</template>

<!-- import { AMapManager } from "vue-amap"; -->

<script>
	// import {
	// 	AMapManager
	// } from "vue-amap";
	// let amapManager = new AMapManager();
	export default {
		data() {
			const self = this;
			return {
				classifyNo: '',
				address: null,
				searchKey: '',
				searchList: [],
				amapManager,
				markers: [],
				marker: "",
				searchOption: {
					// city: "北京", //搜索范围
					// citylimit: true, //限制搜索范围
					city: "",
					citylimit: false, // 不限制搜索范围搜索，比如想全国搜索
				},
				zoom: 15,
				lng: '',
				lat: '',
				center: [],
				// locate:false,
				loaded: false,
				events: {
					init: (o) => {
						console.log('init', o);
						o.getCity((result) => {
							console.log(result);
							let par = document.getElementsByClassName("search-box-wrapper")[0];
							console.log(par.firstChild);
							par.firstChild.setAttribute(
								"placeholder",
								"您可以在这里输入要搜索的地址"
							);
							console.log(result, 'ww');
							//todo 定位到搜索位置
							this.searchOption.city = result.city;
						});
					},
					moveend: () => {},
					zoomchange: () => {},
					click: (e) => {
						let {
							lng,
							lat
						} = e.lnglat
						self.lng = lng
						self.lat = lat
						AMap.plugin('AMap.Geocoder', function() {
							console.log(AMap.Geocoder, [lng, lat]);
							// 逆向地理编码方法
							var geocoder = new AMap.Geocoder({
								radius: 1000,
								extensions: 'all'
							})
							geocoder.getAddress([lng, lat], (status, result) => {
								if (status === 'complete' && result.info === 'OK') {
									if (result && result.regeocode) {
										self.address = result.regeocode.formattedAddress
										self.markers = [];
										let formattedAddress = result.regeocode.formattedAddress
										let index = formattedAddress.indexOf('区') + 1
										let str = formattedAddress.slice(index)
										uni.setStorageSync('formatted_address', str)
										self.searchKey = str

										const obj = {
											position: [lng, lat],
											text: str,
											offset: [0, 30],
										};
										self.markers.push(obj);
										self.center = [lng, lat]
										self.$nextTick()
									}
								}
							})
						})

					},
				},
				// 一些工具插件
				plugin: [{
						// 定位
						pName: "Geolocation",
						events: {
							init(o) {
								if(uni.getStorageSync('lng') && uni.getStorageSync('lat')) {
									let o = amapManager.getMap();
									if (!self.marker) {
										self.marker = new AMap.Marker({
											position: self.center,
										});
										self.marker.setMap(o);
									}
									self.marker.setPosition(self.center);
									return
								}
								// o 是高德地图定位插件实例
								o.getCurrentPosition((status, result) => {
									// console.log(JSON.stringify(result));
									if (result && result.position) {
										self.lng = result.position.lng;
										self.lat = result.position.lat;
										self.address = result.formattedAddress;
										self.center = [self.lng, self.lat];
										//   console.log(self.center, 99666);
										let o = amapManager.getMap();
										if (!self.marker) {
											self.marker = new AMap.Marker({
												position: self.center,
											});
											self.marker.setMap(o);
										}
										self.marker.setPosition(self.center);
									} else {
										self.$message.error("位置信息，获取失败！")
									}
								});
							},
						},
					},
					{
						// 工具栏
						pName: "ToolBar",
						// locate:true, // 定位
						// direction:true, // 方向键盘是否可见
						liteStyle: true, // 精简模式

						// position:"RB", // 位置，默认为LT 代表 左上方
					},
					"Scale", // 比例尺
					{
						// 地图类型
						pName: "MapType",
						defaultType: 0,
						events: {
							init(o) {
								console.log(o);
							},
						},
					},
				],
			};
		},
		onLoad(e) {
			this.classifyNo = e.classifyNo
		},
		created() {
			this.searchKey = uni.getStorageSync('formatted_address')
			this.lng = uni.getStorageSync('lng')
			this.lat = uni.getStorageSync('lat')
			this.center = [this.lng, this.lat]
		},
		methods: {
			goCustom() {
				console.log('goCustom','搜索');
				console.log(this.searchList[0]);
			},
			goSearch(item) {
				let {lng,lat} = item.location
				let address = `${item.district}${item.name}`
				uni.setStorageSync('formatted_address',address)
				uni.setStorageSync('lng',lng)
				uni.setStorageSync('lat',lat)
				this.back()
			},
			searchChange(e) {
				if(e === '') {
					this.searchList = []
					return 
				}
				
				AMap.plugin('AMap.Autocomplete', ()=>{
				  // 实例化Autocomplete
				  var autoOptions = {
				    //city 限定城市，默认全国
				    city: '全国'
				  }
				  var autoComplete= new AMap.Autocomplete(autoOptions);
				  autoComplete.search(e, (status, result)=> {
				    // 搜索成功时，result即是对应的匹配数据
					if(status == 'complete') {
						this.searchList = result.tips
						console.log(result.tips);
					}
				  })
				})
			},
			input(pois) {
				console.log(pois);
				// if (pois.length > 0) {
				// 	console.log(pois);
				// 	let {
				// 		lng,
				// 		lat,
				// 		name,
				// 		location,
				// 		address
				// 	} = pois[0];
				// 	//?显示
				// 	this.markers = [];
				// 	const obj = {
				// 		position: [lng, lat],
				// 		text: address + name,
				// 		offset: [0, 30],
				// 	};
				// 	this.markers.push(obj);
				// 	this.address = address + name;

				// 	let center = [lng, lat];
				// 	this.lng = lng;
				// 	this.lat = lat;
				// 	this.center = [lng, lat];
				// 	let o = amapManager.getMap();
				// 	if (!this.marker) {
				// 		this.marker = new AMap.Marker({
				// 			position: center,
				// 		});
				// 		this.marker.setMap(o);
				// 	}
				// 	this.marker.setPosition(center);
				// }
			},
			back() {
				let {classifyNo} = this
				uni.redirectTo({
					url: `/subPage1/socialized-service/farm-service/normalUser/serviceSelect/service-organization/information-filling?classifyNo=${classifyNo}`
				})
			}
		},
	};
</script>

<style lang="scss" scoped>
	/deep/ .uni-navbar {
		position: fixed;
		top: 0;
		left: 0;
		z-index: 999;
		// pointer-events: none;
	}

	/deep/.uni-navbar__content,
	/deep/.uni-navbar__header {
		border-bottom: none !important;
	}

	.map-container {
		width: 100%;
		height: calc(100% - 130rpx);
		padding-top: 130rpx;
	}


	.amap-demo {
		height: 100%;
	}

	.search-box {
		width: 100%;
		position: fixed;
		top: -20rpx;
		left: 50%;
		transform: translateY(50%) translateX(-50%);
		border: 2rpx solid #ccc;
		border-radius: 60rpx;
		z-index: 9999;
	}
	.ul {
		position: absolute;
		width: 100%;
		padding: 0 20rpx;
		background-color: #fff;
		max-height: 60%;
		top: 120rpx;
		z-index: 99999;
		overflow-y: auto;
		
		.li {
				margin-bottom: 10rpx;
			}
		
	}

	.amap-page-container {
		position: relative;
	}

	/deep/.amap-marker-content {
		width: 240rpx !important;
		padding: 2px 0;
		display: flex !important;
		min-height: 40rpx;
		flex-wrap: wrap;
		white-space: wrap !important;
		overflow: none !important;
		text-overflow: none !important;
	}

	/deep/ .amap-overlay-text-container {
		word-break: normal;
		white-space: wrap !important;
	}
</style>